package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartcampusbackend.mapper.ResourceDownloadMapper;
import com.smartcampusbackend.mapper.ResourceMapper;
import com.smartcampusbackend.mapper.ResourceBookingMapper;
import com.smartcampusbackend.model.Resource;
import com.smartcampusbackend.model.ResourceDownload;
import com.smartcampusbackend.model.ResourceBooking;
import com.smartcampusbackend.service.ResourceService;
import com.smartcampusbackend.util.FileUploadUtil;
import com.smartcampusbackend.util.ResourceIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.util.UUID;
import java.util.Set;
import java.util.List;
import java.util.Date;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;
    
    @Autowired
    private ResourceDownloadMapper resourceDownloadMapper;

    @Autowired
    private ResourceBookingMapper resourceBookingMapper;

    @Autowired
    private ResourceIdGenerator resourceIdGenerator;

    @Override
    @Transactional
    public Map<String, Object> uploadResource(Resource resource, MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证资源信息
            if (resource.getTitle() == null || resource.getTitle().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源标题不能为空");
                return result;
            }
            
            if (resource.getDescription() == null || resource.getDescription().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源描述不能为空");
                return result;
            }
            
            if (resource.getCategory() == null || resource.getCategory().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源分类不能为空");
                return result;
            }
            
            if (resource.getType() == null || resource.getType().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源类型不能为空");
                return result;
            }
            
            // 根据资源类型处理
            if ("DOCUMENT".equals(resource.getType())) {
                // 文档类型必须上传文件
                if (file == null || file.isEmpty()) {
                    result.put("code", 400);
                    result.put("message", "文档类型资源必须上传文件");
                    return result;
                }
                
                // 验证文件大小（50MB限制）
                if (file.getSize() > 50 * 1024 * 1024) {
                    result.put("code", 400);
                    result.put("message", "文件大小不能超过50MB");
                    return result;
                }
                
                // 验证文件类型
                String originalFilename = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                }
                
                // 允许的文件类型
                Set<String> allowedExtensions = Set.of("pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt", "zip", "rar");
                if (!allowedExtensions.contains(fileExtension)) {
                    result.put("code", 400);
                    result.put("message", "不支持的文件类型，请上传PDF、Word、PPT、Excel、TXT、ZIP、RAR格式文件");
                    return result;
                }
                
                // 使用FileUploadUtil上传文件
                String fileUrl = FileUploadUtil.uploadAttachment(file);
                
                // 设置文件信息
                resource.setFileUrl(fileUrl);
                resource.setFileName(originalFilename);
                resource.setFileSize(file.getSize());
                resource.setFileExtension(fileExtension);
                
            } else if ("EQUIPMENT".equals(resource.getType())) {
                // 设备类型不需要文件，但需要设备信息
                if (resource.getEquipmentInfo() == null || resource.getEquipmentInfo().trim().isEmpty()) {
                    result.put("code", 400);
                    result.put("message", "设备类型资源必须提供设备信息");
                    return result;
                }
                
                // 清空文件相关字段
                resource.setFileUrl(null);
                resource.setFileName(null);
                resource.setFileSize(null);
                resource.setFileExtension(null);
            } else {
                result.put("code", 400);
                result.put("message", "不支持的资源类型");
                return result;
            }
            
            // 设置默认值
            resource.setStatus("PENDING"); // 默认为待审核状态
            resource.setDownloadCount(0);
            resource.setViewCount(0);
            resource.setCreateTime(LocalDateTime.now());
            resource.setUpdateTime(LocalDateTime.now());
            
            // 生成主键ID（32位UUID）
            String id = UUID.randomUUID().toString().replace("-", "");
            resource.setId(id);
            
            // 生成8位资源编号
            String resourceId = resourceIdGenerator.generateResourceId();
            resource.setResourceId(resourceId);
            
            // 清空审核相关字段（新上传的资源）
            resource.setReviewerId(null);
            resource.setReviewerName(null);
            resource.setReviewTime(null);
            resource.setReviewComment(null);
            
            // 保存到数据库
            int insertResult = resourceMapper.insert(resource);
            if (insertResult > 0) {
                result.put("code", 200);
                result.put("message", "资源上传成功，等待审核");
                result.put("data", resource);
            } else {
                result.put("code", 500);
                result.put("message", "资源上传失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "上传异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> updateResource(Resource resource, MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取原资源信息
            Resource originalResource = resourceMapper.selectById(resource.getId());
            if (originalResource == null) {
                result.put("code", 404);
                result.put("message", "资源不存在");
                return result;
            }
            
            // 只能修改已通过状态的资源
            if (!"APPROVED".equals(originalResource.getStatus())) {
                result.put("code", 400);
                result.put("message", "只能修改已通过状态的资源");
                return result;
            }
            
            // 验证资源信息
            if (resource.getTitle() == null || resource.getTitle().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源标题不能为空");
                return result;
            }
            
            if (resource.getDescription() == null || resource.getDescription().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源描述不能为空");
                return result;
            }
            
            if (resource.getCategory() == null || resource.getCategory().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源分类不能为空");
                return result;
            }
            
            if (resource.getType() == null || resource.getType().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "资源类型不能为空");
                return result;
            }
            
            // 处理文件更新（仅文档类型）
            if ("DOCUMENT".equals(resource.getType()) && file != null && !file.isEmpty()) {
                // 验证文件大小（50MB限制）
                if (file.getSize() > 50 * 1024 * 1024) {
                    result.put("code", 400);
                    result.put("message", "文件大小不能超过50MB");
                    return result;
                }
                
                // 验证文件类型
                String originalFilename = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                }
                
                // 允许的文件类型
                Set<String> allowedExtensions = Set.of("pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt", "zip", "rar");
                if (!allowedExtensions.contains(fileExtension)) {
                    result.put("code", 400);
                    result.put("message", "不支持的文件类型，请上传PDF、Word、PPT、Excel、TXT、ZIP、RAR格式文件");
                    return result;
                }
                
                // 删除原文件
                if (originalResource.getFileUrl() != null && !originalResource.getFileUrl().isEmpty()) {
                    FileUploadUtil.deleteAvatar(originalResource.getFileUrl());
                }
                
                // 使用FileUploadUtil上传新文件
                String fileUrl = FileUploadUtil.uploadAttachment(file);
                
                // 设置新文件信息
                resource.setFileUrl(fileUrl);
                resource.setFileName(originalFilename);
                resource.setFileSize(file.getSize());
                resource.setFileExtension(fileExtension);
                
            } else {
                // 保持原文件信息
                resource.setFileUrl(originalResource.getFileUrl());
                resource.setFileName(originalResource.getFileName());
                resource.setFileSize(originalResource.getFileSize());
                resource.setFileExtension(originalResource.getFileExtension());
            }
            
            // 保持原有信息
            resource.setUploaderId(originalResource.getUploaderId());
            resource.setUploaderName(originalResource.getUploaderName());
            resource.setStatus(originalResource.getStatus());
            resource.setReviewerId(originalResource.getReviewerId());
            resource.setReviewerName(originalResource.getReviewerName());
            resource.setReviewTime(originalResource.getReviewTime());
            resource.setReviewComment(originalResource.getReviewComment());
            resource.setDownloadCount(originalResource.getDownloadCount());
            resource.setViewCount(originalResource.getViewCount());
            resource.setCreateTime(originalResource.getCreateTime());
            resource.setUpdateTime(LocalDateTime.now());
            
            // 更新数据库
            int updateResult = resourceMapper.updateById(resource);
            if (updateResult > 0) {
                result.put("code", 200);
                result.put("message", "资源更新成功");
                result.put("data", resource);
            } else {
                result.put("code", 500);
                result.put("message", "资源更新失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> deleteResource(String id, String userId, String userRole) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Resource resource = resourceMapper.selectById(id);
            if (resource == null) {
                result.put("code", 404);
                result.put("message", "资源不存在");
                return result;
            }
            
            // 权限检查：只有管理员或资源上传者可以删除
            if (!"ADMIN".equals(userRole) && !resource.getUploaderId().equals(userId)) {
                result.put("code", 403);
                result.put("message", "权限不足，只能删除自己上传的资源");
                return result;
            }
            
            // 删除文件（如果存在）
            if (resource.getFileUrl() != null && !resource.getFileUrl().isEmpty()) {
                FileUploadUtil.deleteAvatar(resource.getFileUrl());
            }
            
            // 删除数据库记录
            int deleteResult = resourceMapper.deleteById(id);
            if (deleteResult > 0) {
                result.put("code", 200);
                result.put("message", "资源删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "资源删除失败");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getResourceById(String id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Resource resource = resourceMapper.selectById(id);
            if (resource == null) {
                result.put("code", 404);
                result.put("message", "资源不存在");
                return result;
            }
            
            // 增加浏览次数
            resource.setViewCount(resource.getViewCount() + 1);
            resourceMapper.updateById(resource);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", resource);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取资源异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public IPage<Resource> getResourceList(Map<String, Object> params) {
        Page<Resource> page = new Page<>(
            Integer.parseInt(params.getOrDefault("current", "1").toString()),
            Integer.parseInt(params.getOrDefault("size", "10").toString())
        );
        
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        
        // 只显示已审核通过的资源
        wrapper.eq(Resource::getStatus, "APPROVED");
        
        // 分类筛选
        if (params.containsKey("category") && params.get("category") != null) {
            wrapper.eq(Resource::getCategory, params.get("category"));
        }
        
        // 类型筛选
        if (params.containsKey("type") && params.get("type") != null) {
            wrapper.eq(Resource::getType, params.get("type"));
        }
        
        // 关键词搜索
        if (params.containsKey("keyword") && params.get("keyword") != null) {
            String keyword = params.get("keyword").toString();
            wrapper.and(w -> w.like(Resource::getTitle, keyword)
                .or().like(Resource::getDescription, keyword)
                .or().like(Resource::getTags, keyword));
        }
        
        // 排序
        wrapper.orderByDesc(Resource::getCreateTime);
        
        return resourceMapper.selectPage(page, wrapper);
    }

    @Override
    public IPage<Resource> getAllResources(Map<String, Object> params) {
        Page<Resource> page = new Page<>(
            Integer.parseInt(params.getOrDefault("current", "1").toString()),
            Integer.parseInt(params.getOrDefault("size", "10").toString())
        );
        
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        
        // 分类筛选
        if (params.containsKey("category") && params.get("category") != null) {
            wrapper.eq(Resource::getCategory, params.get("category"));
        }
        
        // 类型筛选
        if (params.containsKey("type") && params.get("type") != null) {
            wrapper.eq(Resource::getType, params.get("type"));
        }
        
        // 状态筛选
        if (params.containsKey("status") && params.get("status") != null) {
            wrapper.eq(Resource::getStatus, params.get("status"));
        }
        
        // 关键词搜索
        if (params.containsKey("keyword") && params.get("keyword") != null) {
            String keyword = params.get("keyword").toString();
            wrapper.and(w -> w.like(Resource::getTitle, keyword)
                .or().like(Resource::getDescription, keyword)
                .or().like(Resource::getTags, keyword)
                .or().like(Resource::getUploaderName, keyword));
        }
        
        // 按ID降序排序（最新的资源在前面）
        wrapper.orderByDesc(Resource::getId);
        
        return resourceMapper.selectPage(page, wrapper);
    }

    @Override
    public IPage<Resource> getMyResources(String userId, Map<String, Object> params) {
        Page<Resource> page = new Page<>(
            Integer.parseInt(params.getOrDefault("current", "1").toString()),
            Integer.parseInt(params.getOrDefault("size", "10").toString())
        );
        
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getUploaderId, userId);
        
        // 状态筛选
        if (params.containsKey("status") && params.get("status") != null) {
            wrapper.eq(Resource::getStatus, params.get("status"));
        }
        
        // 排序
        wrapper.orderByDesc(Resource::getCreateTime);
        
        return resourceMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public Map<String, Object> reviewResource(String id, String status, String comment, String reviewerId, String reviewerName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Resource resource = resourceMapper.selectById(id);
            if (resource == null) {
                result.put("code", 404);
                result.put("message", "资源不存在");
                return result;
            }
            
            // 检查资源状态
            if (!"PENDING".equals(resource.getStatus())) {
                result.put("code", 400);
                result.put("message", "只能审核待审核状态的资源");
                return result;
            }
            
            if ("REJECTED".equals(status)) {
                // 拒绝资源：删除文件和数据库记录
                try {
                    // 删除文件（如果存在）
                    if (resource.getFileUrl() != null && !resource.getFileUrl().isEmpty()) {
                        FileUploadUtil.deleteAvatar(resource.getFileUrl());
                    }
                    
                    // 删除数据库记录
                    resourceMapper.deleteById(id);
                    
                    result.put("code", 200);
                    result.put("message", "资源已拒绝并删除");
                    result.put("data", null);
                    
                } catch (Exception e) {
                    result.put("code", 500);
                    result.put("message", "删除资源失败：" + e.getMessage());
                }
                
            } else if ("APPROVED".equals(status)) {
                // 通过资源：更新状态和审核信息
                resource.setStatus(status);
                resource.setReviewerId(reviewerId);
                resource.setReviewerName(reviewerName);
                resource.setReviewTime(LocalDateTime.now());
                resource.setReviewComment(comment);
                resource.setUpdateTime(LocalDateTime.now());
                
                int updateResult = resourceMapper.updateById(resource);
                if (updateResult > 0) {
                    result.put("code", 200);
                    result.put("message", "审核通过");
                    result.put("data", resource);
                } else {
                    result.put("code", 500);
                    result.put("message", "审核失败");
                }
                
            } else {
                result.put("code", 400);
                result.put("message", "无效的审核状态");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "审核异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public IPage<Resource> getPendingResources(Map<String, Object> params) {
        Page<Resource> page = new Page<>(
            Integer.parseInt(params.getOrDefault("current", "1").toString()),
            Integer.parseInt(params.getOrDefault("size", "10").toString())
        );
        
        LambdaQueryWrapper<Resource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Resource::getStatus, "PENDING");
        wrapper.orderByDesc(Resource::getCreateTime);
        
        return resourceMapper.selectPage(page, wrapper);
    }

    @Override
    @Transactional
    public Map<String, Object> downloadResource(String id, String userId, String userName, String ipAddress, String userAgent) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Resource resource = resourceMapper.selectById(id);
            if (resource == null) {
                result.put("code", 404);
                result.put("message", "资源不存在");
                return result;
            }
            
            if (!"APPROVED".equals(resource.getStatus())) {
                result.put("code", 403);
                result.put("message", "资源未通过审核，无法下载");
                return result;
            }
            
            if (!"DOCUMENT".equals(resource.getType())) {
                result.put("code", 400);
                result.put("message", "只有文档类型资源可以下载");
                return result;
            }
            
            // 记录下载记录
            ResourceDownload download = new ResourceDownload();
            download.setResourceId(id);
            download.setUserId(userId);
            download.setUserName(userName);
            download.setDownloadTime(LocalDateTime.now());
            download.setIpAddress(ipAddress);
            download.setUserAgent(userAgent);
            resourceDownloadMapper.insert(download);
            
            // 更新下载次数
            resource.setDownloadCount(resource.getDownloadCount() + 1);
            resourceMapper.updateById(resource);
            
            result.put("code", 200);
            result.put("message", "下载成功");
            result.put("data", resource);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "下载异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getDownloadStatistics(String resourceId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            LambdaQueryWrapper<ResourceDownload> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ResourceDownload::getResourceId, resourceId);
            
            long totalDownloads = resourceDownloadMapper.selectCount(wrapper);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", totalDownloads);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取统计异常：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public IPage<Resource> searchResources(Map<String, Object> params) {
        return getResourceList(params);
    }

    @Override
    public Map<String, Object> getResourceCategories() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, String> categories = new HashMap<>();
            categories.put("TEACHING", "教学课件");
            categories.put("SCIENTIFIC", "科研资料");
            categories.put("LITERATURE", "图书文献");
            categories.put("EQUIPMENT", "共享设备");
            
            Map<String, String> types = new HashMap<>();
            types.put("DOCUMENT", "文档");
            types.put("EQUIPMENT", "设备");
            
            Map<String, Object> data = new HashMap<>();
            data.put("categories", categories);
            data.put("types", types);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", data);
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取分类异常：" + e.getMessage());
        }
        
        return result;
    }

    // 设备预约相关
    @Override
    public int createBooking(ResourceBooking booking) {
        booking.setStatus("PENDING");
        return resourceBookingMapper.insert(booking);
    }

    @Override
    public int updateBooking(ResourceBooking booking) {
        return resourceBookingMapper.update(booking);
    }

    @Override
    public int cancelBooking(Integer bookingId, Integer userId) {
        ResourceBooking booking = resourceBookingMapper.selectById(bookingId);
        if (booking != null && booking.getUserId().equals(userId) && "PENDING".equals(booking.getStatus())) {
            return resourceBookingMapper.deleteById(bookingId);
        }
        return 0;
    }

    @Override
    public List<ResourceBooking> getBookingsByUser(Integer userId) {
        return resourceBookingMapper.selectByUserId(userId);
    }

    @Override
    public List<ResourceBooking> getBookingsByStatus(String status) {
        return resourceBookingMapper.selectByStatus(status);
    }

    @Override
    public List<ResourceBooking> getAllBookings() {
        return resourceBookingMapper.selectAll();
    }

    @Override
    public List<ResourceBooking> getBookingsByResourceIdAndDate(String resourceId, Date bookingDate) {
        return resourceBookingMapper.selectByResourceIdAndDate(resourceId, bookingDate);
    }

    @Override
    public Resource getResourceByIdObj(String id) {
        return resourceMapper.selectById(id);
    }
} 